import * as types from "./types";

const setFrom = from => ({
  type: types.SET_FROM,
  payload: from
});

const setTo = to => ({
  type: types.SET_TO,
  payload: to
});

const setIsLoadingCityData = isLoadingCityData => ({
  type: types.SET_IS_LOADING_CITY_DATA,
  payload: isLoadingCityData
});

const setCityData = cityDate => ({
  type: types.SET_CITY_DATA,
  payload: cityDate
});

const showCitySelector = currentSelectingLeftCity => {
  return dispatch => {
    dispatch({
      type: types.SET_IS_CITY_SELECTOR_VISIBLE,
      payload: true
    });

    dispatch({
      type: types.SET_CURRENT_SELECTING_LEFT_CITY,
      payload: currentSelectingLeftCity
    });
  };
};

const hideCitySelector = () => ({
  type: types.SET_IS_CITY_SELECTOR_VISIBLE,
  payload: false
});

const setSelectedCity = city => {
  return (dispatch, getState) => {
    const { currentSelectingLeftCity } = getState();

    if (currentSelectingLeftCity) {
      dispatch(setFrom(city));
    } else {
      dispatch(setTo(city));
    }

    dispatch(hideCitySelector());
  };
};

const exchangeFromTo = () => {
  return (dispatch, getState) => {
    const { from, to } = getState();
    dispatch(setFrom(to));
    dispatch(setTo(from));
  };
};

const showDateSelector = () => ({
  type: types.SET_IS_DATE_SELECTOR_VISIBLE,
  payload: true
});

const hideDateSelector = () => ({
  type: types.SET_IS_DATE_SELECTOR_VISIBLE,
  payload: false
});

const setDepartDate = departDate => ({
  type: types.SET_DEPART_DATE,
  payload: departDate
});

const toggleHighSpeed = () => {
  return (dispatch, getState) => {
    const { highSpeed } = getState();
    dispatch({
      type: types.SET_HIGH_SPEED,
      payload: !highSpeed
    });
  };
};

const fetchCityData = () => {
  return (dispatch, getState) => {
    const { isLoadingCityData } = getState();

    if (isLoadingCityData) return;

    // 加入缓存
    const cache = JSON.parse(localStorage.getItem("city_data_cache") || "{}");
    if (Date.now() < cache.expires) {
      dispatch(setCityData(cache.data));
      return;
    }

    dispatch(setIsLoadingCityData(true));

    fetch("/api/cities?_" + Date.now())
      .then(res => res.json())
      .then(cityData => {
        dispatch(setCityData(cityData));

        localStorage.setItem(
          "city_data_cache",
          JSON.stringify({
            expires: Date.now() + 60 * 1000,
            data: cityData
          })
        );

        dispatch(setIsLoadingCityData(false));
      })
      .catch(() => {
        dispatch(setIsLoadingCityData(false));
      });
  };
};

export {
  setFrom,
  setTo,
  setIsLoadingCityData,
  setCityData,
  setSelectedCity,
  setDepartDate,
  exchangeFromTo,
  showCitySelector,
  hideCitySelector,
  showDateSelector,
  hideDateSelector,
  toggleHighSpeed,
  fetchCityData
};
